#pragma once

#include "simple_rest_api.h"
#include <string>
#include <functional>
#include <iostream>
namespace SimpleRest {

// 路由构建器
class RouteBuilder {
public:
    RouteBuilder(RestApiHandler& api, const std::string& uri, HttpMethod method)
        : api_(api), uri_(uri), method_(method) {}

    // 设置请求处理函数
    RestApiHandler&& handle(std::function<HttpResponse(const HttpRequest&)> handler) {
        api_.addRoute(uri_, method_, handler);
        return std::move(api_);
    }

private:
    RestApiHandler& api_;
    std::string uri_;
    HttpMethod method_;
};

// API装饰器
class ApiDecorator {
public:
    explicit ApiDecorator(RestApiHandler& api) : api_(api) {}

    // 定义GET路由
    RouteBuilder&& GET(const std::string& uri) {
        return RouteBuilder(api_, uri, HttpMethod::GET);
    }

    // 定义POST路由
    RouteBuilder&& POST(const std::string& uri) {
        return RouteBuilder(api_, uri, HttpMethod::POST);
    }

    // 定义PUT路由
    RouteBuilder&& PUT(const std::string& uri) {
        return RouteBuilder(api_, uri, HttpMethod::PUT);
    }

    // 定义DELETE路由
    RouteBuilder&& DELETE(const std::string& uri) {
        return RouteBuilder(api_, uri, HttpMethod::DELETE);
    }

    // 持久化存储数据到文件
    ApiDecorator& saveDataToFile(const std::string& filename, const json& data) {
        api_.saveDataToFile(filename, data);
        return *this;
    }

    // 测试API
    ApiDecorator& testRoute(HttpMethod method, const std::string& uri, const json& body = json::object()) {
        HttpResponse response = api_.testRoute(method, uri, body);
        std::cout << "Request: " << methodToString(method) << " " << uri << std::endl;
        std::cout << "Response: " << response.status_code << " " << response.body.dump(4) << std::endl;
        return *this;
    }

private:
    RestApiHandler& api_;

    std::string methodToString(HttpMethod method) {
        switch (method) {
            case HttpMethod::GET: return "GET";
            case HttpMethod::POST: return "POST";
            case HttpMethod::PUT: return "PUT";
            case HttpMethod::DELETE: return "DELETE";
            default: return "UNKNOWN";
        }
    }
};

} // namespace SimpleRest